/* 
 * Author: Alexander Rauser, arauser.org
 * Date: August 2008
 * Copyright: 2008
 * Licensed under Creative Commons Attribution 3.0 Unported
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

/// <summary>
/// This class takes the uploaded file and saves it on the server.
/// </summary>
public partial class Default : System.Web.UI.Page
{

	// The folder where we store our files relative to the web root.
    private static string uploadpath = @"uploads";

	
    protected void Page_Load(object sender, EventArgs e)
    {
	
		// Each file will be stored in a new folder using a GUID, we don't use a database so we need to distinguish between files with the same name.
        string GUID = Guid.NewGuid().ToString();
        string filename = "";

        try
        {
            
                // Create a uique directory
                DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(Path.Combine(@"~\"+uploadpath,GUID)));
                dirInfo.Create();

				// Uploads all posted files, in our case it is only one per request.
                foreach (string fileKey in System.Web.HttpContext.Current.Request.Files)
                {
                    HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[fileKey];
                    file.SaveAs(Path.Combine(Server.MapPath(Path.Combine(@"~\"+uploadpath, GUID)), file.FileName));

                    filename = file.FileName;
                }
            
            
            // Remove old folders
            DeleteOldFiles();
        }
        catch(Exception ex)
        {
            Log.Write(ex.StackTrace.ToString());
        }

		// Return the absolute URL to the uploaded file
        string url = Request.Url.ToString().Substring(0, Request.Url.ToString().LastIndexOf("/") + 1);
        Response.Write(url + GUID + "/" + filename);
    }

    /// <summary>
    /// Delete all folders that are older then 10 days.
    /// </summary>
    private void DeleteOldFiles()
    {
        DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(@"~\"+uploadpath));
        foreach (DirectoryInfo dir in dirInfo.GetDirectories())
        {
            TimeSpan span = DateTime.Now.Subtract(dir.CreationTime);

            if (span.TotalDays > 10)
            {
                dir.Delete();
            }
        }
    }
}
